import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import autoprefixer from "autoprefixer"
import path from "path"; //这个path用到了上面安装的@types/node
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { fileURLToPath, URL } from "node:url"
import Icons from "unplugin-icons/vite";
// import { terser } from 'rollup-plugin-terser';
// import viteImagemin from 'vite-plugin-imagemin';
import IconsResolver from "unplugin-icons/resolver";
// import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
// import { PROXY_URL } from "./src/config";
import { wrapperEnv } from "./build/getEnv"
import { createProxy } from "./build/proxy"
// import nodeResolve from 'vite-plugin-node-resolve'
const pathSrc = path.resolve(__dirname, "src");
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  const viteEnv = wrapperEnv(env)
  return {
    base: viteEnv.VITE_PUBLIC_PATH,

    plugins: [
      vue(),
      AutoImport({
        imports: [
          "vue",
          "vue-router",
          "pinia",
          {
            axios: [
              ["default", "axios"], // import { default as axios } from "axios",
            ],
            // "lodash": [
            //   // 配置哪些方法自动引入
            //   "concat", // 相对于 import { concat } from "lodash"
            //   ["compact", "cp"], // 相对于 import { compact as cp } from "lodash"
            // ],
          },
        ],
        // 配置哪些本地目录支持自动引入
        dirs: [
          "./src/utils/**",
          "./src/api",
          "./src/stores",
          "./src/routers",
          "./src/config",
          "./src/views/**"
        ],
        eslintrc: {
          enabled: true, // 是否自动生成 eslint 规则，建议生成之后设置 false
          filepath: "./.eslintrc-auto-import.json", // 指定自动导入函数 eslint 规则的文件
        },
        resolvers: [ElementPlusResolver(), IconsResolver({}),],
      }),
      // terser({
      //   terserOptions: {
      //     compress: {
      //       drop_console: true, // 去除console
      //     }
      //   }
      // }),
      // viteImagemin({
      //   gifsicle: {
      //     optimizationLevel: 7,
      //     interlaced: false,
      //   },
      //   optipng: {
      //     optimizationLevel: 7,
      //   },
      //   mozjpeg: {
      //     quality: 20,
      //   },
      //   pngquant: {
      //     quality: [0.8, 0.9],
      //     speed: 4,
      //   },
      //   svgo: {
      //     plugins: [
      //       {
      //         name: 'removeViewBox',
      //       },
      //       {
      //         name: 'removeEmptyAttrs',
      //         active: false,
      //       },
      //     ],
      //   },
      // }),
      Components({
        resolvers: [ElementPlusResolver(), IconsResolver()],
        // 配置本地组件库的自动引入
        dts: path.resolve(pathSrc, "types", "components.d.ts"), // 指定自动导入组件TS类型声明文件路径位置，默认根目录
        dirs: ["./src/components"],
        vueTemplate: true, // 是否在 vue 模板中自动导入
      }),
      Icons({
        // 自动安装图标库
        autoInstall: true,
      }),
      // nodeResolve(),
    ],
    css: {
      postcss: {
        plugins: [
          autoprefixer({
            overrideBrowserslist: ["Android 4.1", "iOS 7.1", "Chrome > 31", "ff > 31", "> 1%"],
            grid: true,
          }),
        ],
      },
    },
    esbuild: {
      // 打包时删除所有 console.log 和 debugger 语句
      pure: viteEnv.VITE_DROP_CONSOLE ? ["console.log", "debugger"] : [],
    },
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
        // 'pdfjs-dist/build/pdf': require.resolve('pdfjs-dist/build/pdf'),
        // 'pdfjs-dist': resolve(__dirname, 'node_modules/pdfjs-dist'),
      },
      extensions: [".js", ".json", ".ts"], // 使用路径别名时想要省略的后缀名，可以自己 增减
    },
    define: {
      __APP_VERSION__: JSON.stringify(process.env.npm_package_version),
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: true,
    },
    server: {
      host: true, // 监听所有地址，包括局域网和公网地址
      https: false,
      port: viteEnv.VITE_PORT,
      open: viteEnv.VITE_OPEN,
      proxy: createProxy(viteEnv.VITE_PROXY),
      //解决跨域
      // proxy: {
      //   "/api": {
      //     target: "http://localhost:3000",
      //     changeOrigin: true,
      //     rewrite: (path) => path.replace(/^\/api/, ""),
      //   }
      // }
    },
    build: {
      target: 'esnext', // 支持现代浏览器特性
      emptyOutDir: true,
      manifest: false,
      ssrManifest: false,
      // minify: 'terser', // 使用 terser 进行压缩
      terserOptions: {
        // 生产环境移除console、debugger
        compress: {
          drop_console: true,   // 默认false
          drop_debugger: true,  // 默认true
        },
      },
      chunkSizeWarningLimit: 2000,
      reportCompressedSize: false,
      rollupOptions: {
        output: {
          format: 'es', // 使用 ES module 格式输出，利于 Tree Shaking
          // 可以配置输出选项
          manualChunks (id) {
            if (id.includes("node_modules")) {
              // 让每个插件都打包成独立的文件
              return id.toString().split("node_modules/")[1].split("/")[0].toString();
            }
          },
          chunkFileNames: 'js/[name]-[hash].js', // 引入文件名的名称
          entryFileNames: 'js/[name]-[hash].js', // 包的入口文件名称
          assetFileNames: '[ext]/[name]-[hash].[ext]', // 资源文件像 字体，图片等
        },
        input: {
          main: path.resolve(__dirname, './index.html'),
        },
      },
    },
    optimizeDeps: {
      include: [
        `monaco-editor/esm/vs/language/json/json.worker`,
        `monaco-editor/esm/vs/language/css/css.worker`,
        `monaco-editor/esm/vs/language/html/html.worker`,
        `monaco-editor/esm/vs/language/typescript/ts.worker`,
        `monaco-editor/esm/vs/editor/editor.worker`,
      ],
    },
  }

});
